package erz.printing.police.print;

import android.content.Context;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintDocumentInfo;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class PdfAssetPrintAdapter extends PrintDocumentAdapter {
    private String pdfFile;
    private Context context;

    public PdfAssetPrintAdapter(String pdfFile, Context context) {
        this.pdfFile = pdfFile;
        this.context = context;
    }
    @Override
    public void onLayout(PrintAttributes oldAttributes,
                         PrintAttributes newAttributes,
                         CancellationSignal cancellationSignal,
                         PrintDocumentAdapter.LayoutResultCallback callback,
                         Bundle metadata) {
        if (cancellationSignal.isCanceled()) {
            callback.onLayoutCancelled();
            return;
        }
        int contentType = PrintDocumentInfo.CONTENT_TYPE_DOCUMENT;

        PrintDocumentInfo.Builder builder = new PrintDocumentInfo
                .Builder(pdfFile)
                .setContentType(contentType);

        PrintDocumentInfo info = builder.build();
        callback.onLayoutFinished(info, true);
    }

    @Override
    public void onWrite(final PageRange[] pageRanges,
                        final ParcelFileDescriptor destination,
                        final CancellationSignal cancellationSignal,
                        final PrintDocumentAdapter.WriteResultCallback callback) {

        InputStream input = null;
        OutputStream output = null;
        try {
            input = context.getAssets().open(pdfFile);
            output = new FileOutputStream(destination.getFileDescriptor());

            byte[] buf = new byte[4096];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } catch (IOException e) {
            callback.onWriteFailed(e.toString());
            return;
        } finally {
            try {
                if (input != null)
                    input.close();
                if (output != null)
                    output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        callback.onWriteFinished(pageRanges);
    }
}
